<!--
 * @Description: 业务管理系统
 * @Author: fxg
 * @Date: 2020-06-29 11:18:28
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-03-25 16:44:06
-->
<template>
  <div class="pages_content table business">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main>
        <div class="header_right" @click="showCardNav = !showCardNav">
          <div class="title">搜索</div>
          <div>
            <div :class="{ 'arrowTransform': !showCardNav, 'arrowTransformReturn': showCardNav}">
              <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
            </div>
          </div>
        </div>
        <div v-show="showCardNav" class="hr"></div>
        <el-collapse-transition>
          <div v-show="showCardNav">
            <div class="search">
              <span style="display: inline-block;margin-bottom: 10px;">
                <span style="margin-right: 12px;">名称</span>
                <el-input v-model="tableParam.name" style="width: 200px;" clearable placeholder="请输入" />
              </span>
              <span style="margin-left: 24px;">
                <span style="margin-right: 12px;">所属系统</span>
                <el-select v-model="tableParam.systemId" placeholder="请选择" style="width: 20%;max-width: 200px;" clearable>
                  <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </span>
              <span style="margin-left: 24px;">
                <span style="margin-right: 12px;">编码</span>
                <el-input v-model="tableParam.code" style="width: 20%;max-width: 200px;" clearable placeholder="请输入" />
              </span>
              <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="(tableParam.page = 1), queryPage()">查 询</el-button>
              <el-button size="medium" class="bottom_all_two" @click="reset()">重 置</el-button>
            </div>
          </div>
        </el-collapse-transition>
        <div class="hr"></div>
        <div class="card">
          <div class="card_nav">
            <div>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="add()">
                <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                添加
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHANCHU'))!==-1" size="small" class="bottom_two" @click="batchUpdateOrDelete('update_status', 0)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                删除
              </el-button>
            </div>
            <div>
              <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='BAOCUNPXH'))!==-1" :underline="false" @click="updateSortNum()">
                <span class="el-icon--left">
                  <i class="iconfont iconicon_button_sort1"></i>
                </span>
                保持排序号
              </el-link>
              <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px;">
                <el-link :underline="false">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_filtrate"></i>
                  </span>
                  筛选
                </el-link>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(item, index) in table" :key="index">
                    <el-checkbox v-model="item.status">{{ item.label }}</el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='DAOCHU'))!==-1" :underline="false" @click="$Download(DownloadURL, tableParam)">
                <span class="el-icon--left">
                  <i class="iconfont iconicon_button_export1"></i>
                </span>
                导出
              </el-link>
            </div>
          </div>
          <div class="card_info" :style="style">
            <el-table ref="multipleTable" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
              <el-table-column align="center" type="selection" width="50"></el-table-column>
              <template v-for="(item, index) in table">
                <el-table-column v-if="item.status" :key="index" :label="item.label" align="center" :width="item.width">
                  <template slot-scope="scope">
                    <span v-if="scope.row.foreignGrant == 1 && item.label == '是否支持对外授权'" style="color:#00A754;">是</span>
                    <span v-if="scope.row.foreignGrant == 0 && item.label == '是否支持对外授权'" style="color:#969799;">否</span>
                    <el-button v-if="item.label == '操作'&&ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="bottom_one" size="mini" @click="update(scope.row)">
                      <i class="icon iconfont iconicon_button_modification" style="font-size: 12px;"></i>
                      修改
                    </el-button>
                    <span v-if="item.label !== '操作' && item.label !== '是否支持对外授权'">{{ scope.row[item.prop] }}</span>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
          <div class="card_bottom">
            <div class="card_bottom_left">
              <div class="top_page_totle">总共{{ total }}条</div>
              <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" layout="prev, pager, next, jumper" :total="total" @current-change="queryPage()"></el-pagination>
            </div>
            <div>
              <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="queryPage()">刷新</el-button>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="dialogVisible" width="800px" :before-close="resefrom">
      <span slot="title" class="dialog-title">{{ dialogtitle }}</span>
      <div class="dialoginfo">
        <el-form ref="dialogForm" :rules="rules" :inline="true" :model="from" label-width="90px">
          <el-form-item prop="name">
            <span slot="label" style="color:  #FF0000 ;">名称</span>
            <el-input v-model="from.name" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <span slot="label" style="color:  #FF0000 ;">编码</span>
            <el-input v-model="from.code" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item prop="levelNum">
            <span slot="label">等级</span>
            <el-input v-model="from.levelNum" type="Number" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item prop="sortNum">
            <span slot="label">排序号</span>
            <el-input v-model="from.sortNum" type="Number" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item prop="systemId">
            <span slot="label">所属系统</span>
            <el-select v-model="from.systemId" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <div>
            <el-form-item prop="foreignGrant" label-width="110px">
              <span slot="label">是否对外授权</span>
              <el-radio-group v-model="from.foreignGrant">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div>
            <el-form-item prop="tableName">
              <span slot="label">数据表结构</span>
              <el-select v-model="from.tableName" placeholder="请选择" filterable @change="getcolumns(from.tableName)">
                <el-option v-for="item in tables" :key="item.value" :label="item.description" :value="item.tableName"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div>
        <el-button size="small" class="bottom_all" @click="addItemData()">
          <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
          添加
        </el-button>
      </div>
      <el-table :data="from.items" style="width: 100%">
        <el-table-column label="字段名称" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.columnName" style="width:100%" placeholder="请选择" @change="setvalue(scope.row)">
              <el-option v-for="(item, index) in columns" :key="index" :label="`${item.columnName}(${item.description})`" :value="item.columnName"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="字段描述" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.columnComment" style="width:100%"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="是否权限控制" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.columnName == 'ID' ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button size="mini" class="bottom_two" @click="del(scope.$index)">
              <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resefrom()">取 消</el-button>
        <el-button class="bottom_all" @click="save()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import breaDcrumb from "@/components/breadcrumb";
import { mapGetters } from "vuex";
import {
  queryPage,
  saveOrUpdate,
  batchUpdateOrDelete,
  updateSortNum,
  getDetail, Download,
} from "@/api/basedata/DataAccess.js";
import { getTables, getColumns as getCol } from "@/api/common.js";
import { queryPage as querybusinessPage } from "@/api/basedata/business.js";
import { sortReg } from "@/common/RegExp.js";
export default {
  components: {
    breaDcrumb,
  },
  data() {
    var validatePass1 = (rule, value, callback) => {
      if (sortReg(value)) {
        callback();
      } else {
        callback(new Error("请输正整数序号!"));
      }
    };
    return {
      DownloadURL: Download,
      /*添加修改弹窗*/
      dialogVisible: false,
      dialogtitle: "添加数据权限配置",
      options: [],
      tables: [],
      columns: [],
      /*弹要修改过着添加的数据*/
      from: {
        code: "",
        name: "",
        systemId: "",
        levelNum: "",
        foreignGrant: 1,
        sortNum: "",
        tableName: "",
        items: [],
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入编码", trigger: "blur" }],
        tableName: [
          { required: true, message: "请选择表结构", trigger: "change" },
        ],
        levelNum: [{ required: true, message: "请输入等级", trigger: "blur" }],
        sortNum: [{ required: true, message: "请输入排序号", trigger: "blur" },
        { validator: validatePass1, trigger: "blur", }],
      },
      /*判断收起展开*/
      showCardNav: true,
      /*搜索关键字段*/
      /*列表展示*/
      table: [
        { label: "编码", width: "auto", prop: "code", status: true },
        { label: "名称", width: "auto", prop: "name", status: true },
        { label: "所属系统", width: "auto", prop: "systemName", status: true },
        { label: "等级", width: "auto", prop: "levelNum", status: true },
        {
          label: "是否支持对外授权",
          width: "auto",
          prop: "foreignGrant",
          status: true,
        },
        { label: "排序号", width: "auto", prop: "sortNum", status: true },
        { label: "操作", width: "120", prop: "", status: true },
      ],
      /*列表选中的数据集*/
      tableParam: {
        page: 1,
        pageSize: 12,
        code: "",
        name: "",
        systemId: ""
      },
      total: 0,
      ids: [],
      sortIds: [],
      tableData: [],
      oldarr: [],
      ButtonList: []
    };
  },
  beforeCreate() {
    querybusinessPage({ page: 1, pageSize: 999999 }).then((res) => {
      this.options = res.data.data;
    });
    getTables().then((res) => {
      this.tables = res.data;
    });
  },
  mounted() {
    this.ButtonList = this.$ButtonList()
    this.queryPage();
  },
  methods: {
    getcolumns(a) {
      let data = this.tables.find((res) => res.tableName == a)
      getCol({ tableName: data.tableName, database: data.databaseName }).then((res) => {
        this.columns = res.data;
      });
    },
    setvalue(a) {
      this.columns.forEach((item) => {
        if (item.columnName == a.columnName) {
          a.columnComment = item.description;
        }
      });
    },
    /*弹窗列表数据添加*/
    addItemData() {
      const data = {
        columnName: "",
        columnComment: "",
        limitControl: 1,
      };
      this.from.items.push(data);
    },
    del(index) {
      this.from.items.splice(index, 1);
    },
    /*更新排序号*/
    updateSortNum() {
      updateSortNum(this.sortIds).then(() => {
        this.queryPage();
      });
    },
    /*重置*/
    reset() {
      this.tableParam.code = "";
      this.tableParam.name = "";
      this.tableParam.systemId = "";
      this.queryPage();
    },
    /*删除，禁用，启用，排序*/
    batchUpdateOrDelete(type, status) {
      if (this.ids.length == 0) {
        this.$message({
          message: "请选择要操作的数据项",
          type: "warning",
        });
        return;
      }
      if (type === "update_status") {
        this.$confirm("此操作将永久删除该信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        })
          .then(() => {
            batchUpdateOrDelete({
              ids: this.ids,
              status: status,
              type: type,
            }).then(() => {
              this.reset();
            });
          })
          .catch(() => { });
      } else {
        batchUpdateOrDelete({
          ids: this.ids,
          status: status,
          type: type,
        }).then(() => {
          this.queryPage();
        });
      }
    },
    /*保存或修改*/
    save() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          delete this.from.createTime;
          delete this.from.updateTime;
          this.from.items.forEach((item) => {
            delete item.updateTime;
            delete item.createTime;
          });
          let allHasData = this.from.items.filter((item) =>
            this.oldarr.some((items) => item.id == items.id)
          );
          let deleteData = this.oldarr.filter(
            (item) => !allHasData.some((items) => item.id == items.id)
          );
          let addData = this.from.items.filter(
            (item) => !allHasData.some((items) => item.id == items.id)
          );
          deleteData.forEach((res) => {
            res.status = 0;
          });
          this.from.items = [...allHasData, ...addData, ...deleteData];
          saveOrUpdate({ ...this.from }).then((res) => {
            if (res.code * 1 === 1001) {
              this.$message.success("保存成功")
              this.resefrom();
              this.queryPage();
            }

          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resefrom() {
      this.dialogVisible = false;
      this.oldarr = [];
      this.$refs.dialogForm.resetFields();
    },
    /*获取列表*/
    queryPage() {
      queryPage(this.tableParam).then((res) => {
        this.total = res.data.totalRows;
        this.tableData = res.data.data;
      });
    },
    add() {
      this.dialogtitle = "添加数据权限配置";
      this.$data.from = this.$options.data().from;
      this.columns = [];
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate();
      }, 10);
      this.dialogVisible = true;
    },
    update(data) {
      getDetail({ id: data.id }).then((res) => {
        this.from = res.data;
        this.from.enable = JSON.stringify(res.data.enable);
        this.oldarr = JSON.parse(JSON.stringify(res.data)).items;
        this.getcolumns(this.from.tableName);
        this.dialogtitle = "修改数据权限配置";
        this.dialogVisible = true;
      });
    },
    /*批量选择*/
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      this.sortIds = [];
      val.forEach((item) => {
        this.ids.push(item.id);
        this.sortIds.push({ id: item.id, sortNum: item.sortNum });
      });
    },
  },
  computed: {
    ...mapGetters({
      screenWidth: "getscreenWidth",
      screenHeight: "getscreenHeight",
      Collapse: "getsCollapse",
    }),
    style() {
      let num = 0;
      if (this.Collapse) {
        num = this.screenWidth - 124;
      } else {
        num = this.screenWidth - 220;
      }
      return "width:" + num + "px;";
    },
  },
};
</script>
<style lang="scss" scoped>
.business {
  .el-input,
  .el-select {
    width: 260px;
  }
  .textarea_input {
    padding-top: 10px;
    align-items: flex-start;
    height: 70px;
  }
  .textarea {
    width: 530px;
  }
}
</style>
